package com.itheima.service;


import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.CheckItemDao;
import com.itheima.dao.PermissionDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckItem;


import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.PermissionDao;
import com.itheima.pojo.Permission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 权限服务
 */

@Service(interfaceClass = PermissionService.class)
@Transactional
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermissionDao permissionDao;

    //新增检查项
    public void add(Permission permission) {
        permission.setRegtime(new Date());
        permissionDao.add(permission);
    }

    //分页查询
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();//ThreadLocal
        PageHelper.startPage(currentPage,pageSize);//分页插件，会在执行sql之前将分页关键字追加到SQL后面
        Page<Permission> page = permissionDao.findByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    //根据id查询权限
    public Permission findById(Integer id) {
        return permissionDao.findById(id);
    }

    //编辑
    public void edit(Permission permission) {
        permissionDao.edit(permission);
    }

    //根据id删除检查项
    public void delete(Integer id) {
        long count = permissionDao.selectCountByPId(id);
        if(count > 0){
            //已经被关联，不能删除
            throw new RuntimeException(MessageConstant.DELETE_PERMISSION_FALL);
        }else{
            //可以删除
            permissionDao.deleteById(id);
        }
    }

    //批量删除
    @Override
    public void deleteSelect(Integer[] ids) {
        for (Integer id : ids) {
            delete(id);
        }
    }

    public List<Permission> findAll() {
        return permissionDao.findAll ();
    }
}
